package cn.stylefeng.guns.modular.kh.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.kh.entity.KhWare;
import cn.stylefeng.guns.modular.kh.model.params.KhWareParam;
import cn.stylefeng.guns.modular.kh.service.KhWareService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;


/**
 * 可好-波次信息控制器
 *
 * @author zzh
 * @Date 2025-10-21 15:06:17
 */
@Controller
@RequestMapping("/khWare")
public class KhWareController extends BaseController {

    private String PREFIX = "/kh/khWare";

    @Autowired
    private KhWareService khWareService;

    @Autowired
    private DictService dictService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicOperateService basicOperateService;

    /**
     * 跳转到主页面
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("")
    public String index(Model model) {
        List<DictResult> waveNumList = this.dictService.findByDicttypeCode2("KH_BC");
        model.addAttribute("waveNumList", waveNumList);
        return PREFIX + "/khWare.html";
    }

    /**
     * 新增页面
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/add")
    public String add(Model model) {
        List<DictResult> waveNumList = this.dictService.findByDicttypeCode2("KH_BC");
        model.addAttribute("waveNumList", waveNumList);

        User user = userService.getcurrentUser();
        BasicPutgoodsParam q = new BasicPutgoodsParam();
        q.setUnitType("门店");
        List<BasicPutgoodsResult> putgoodsList = basicPutgoodsService.findListBySpec(q, user.getOperateId());
        model.addAttribute("putgoodsList", putgoodsList);

        return PREFIX + "/khWare_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
        User user = userService.getcurrentUser();
        List<DictResult> waveNumList = this.dictService.findByDicttypeCode2("KH_BC");
        model.addAttribute("waveNumList", waveNumList);
        BasicPutgoodsParam q = new BasicPutgoodsParam();
        q.setUnitType("门店");
        List<BasicPutgoodsResult> putgoodsList = basicPutgoodsService.findListBySpec(q, user.getOperateId());
        model.addAttribute("putgoodsList", putgoodsList);
        return PREFIX + "/khWare_edit.html";
    }

    /**
     * 新增接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(KhWareParam khWareParam) {
        User user = userService.getcurrentUser();

        BasicPutgoods basicPutgoods = basicPutgoodsService.getById(khWareParam.getGetUnitId());
        if(ToolUtil.isEmpty(basicPutgoods)){
            return ResponseData.error("收货客户不存在！！");
        }

        Integer count = khWareService.lambdaQuery()
                .eq(KhWare::getGetUnitId,khWareParam.getGetUnitId())
                .count();

        if(count > 0){
            return ResponseData.error("收货客户波次已存在！！");
        }
        khWareParam.setGetUnit(basicPutgoods.getPutgoodsName());
        khWareParam.setGetUnitNumber(basicPutgoods.getUnitNumber());

        khWareParam.setDeliverId(1L);
        khWareParam.setDeptId(user.getDeptId());
        khWareParam.setCreateUser(user.getUserId());
        khWareParam.setCreateTime(new Date());

        if(ToolUtil.isNotEmpty(user.getOperateId())){
            khWareParam.setOperateId(user.getOperateId());
            BasicOperate basicOperateObj = basicOperateService.getById(user.getOperateId());
            khWareParam.setOperateName(basicOperateObj.getOperateName());
        }

        this.khWareService.add(khWareParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(KhWareParam khWareParam) {
        User user = userService.getcurrentUser();
        BasicPutgoods basicPutgoods = basicPutgoodsService.getById(khWareParam.getGetUnitId());
        if(ToolUtil.isEmpty(basicPutgoods)){
            return ResponseData.error("收货客户不存在！！");
        }

        Integer count = khWareService.lambdaQuery()
                .eq(KhWare::getGetUnitId,khWareParam.getGetUnitId())
                .ne(KhWare::getId,khWareParam.getId())
                .count();

        if(count > 0){
            return ResponseData.error("收货客户波次已存在！！");
        }

        khWareParam.setUpdateUser(user.getUserId());
        khWareParam.setUpdateTime(new Date());
        if(ToolUtil.isNotEmpty(user.getOperateId())){
            khWareParam.setOperateId(user.getOperateId());
            BasicOperate basicOperateObj = basicOperateService.getById(user.getOperateId());
            khWareParam.setOperateName(basicOperateObj.getOperateName());
        }

        this.khWareService.update(khWareParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(KhWareParam khWareParam) {
        this.khWareService.delete(khWareParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(KhWareParam khWareParam) {
        KhWare detail = this.khWareService.getById(khWareParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zzh
     * @Date 2025-10-21
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(KhWareParam khWareParam,String condition ) {
        return this.khWareService.findPageBySpec(khWareParam,condition);
    }

    /**
     * 跳转到导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel() {
        return PREFIX + "/import.html";
    }

    /**
     * 导入excel
     */
    @RequestMapping(value = "/importExcel" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExcel(@RequestPart("file") MultipartFile file)  {
        ResponseData data = new ResponseData();
        //
        try {
            data = khWareService.getExceldata(file,userService.getUser());//处理导入数据
        } catch (Exception e) {
            data.setSuccess(false);
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
        String path = "assets/excel/khWare.xls";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("波次信息" + ".xls").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


